<template lang="">
  <el-dialog
    title="Device Details"
    :visible="visible"
    width="50%"
    @close="$emit('warehouse_gate_dall', false)"
    center
  >
    <div>
      <div class="dialog_content_item">
        Device Name:
        <span style="margin-left:5px">{{ useDetail.deviceName }}</span>
      </div>
      <div class="dialog_content_item">
        Device Address:
        <span style="margin-left:5px">{{ useDetail.address }}</span>
      </div>
      <div class="dialog_content_item">
        Device Employ Time:
        <span style="margin-left:5px">{{
          formatSeconds(useDetail.serverTime) || 0
        }}</span>
      </div>
      <div class="dialog_content_item">
        Device Total Order:
        <span style="margin-left:5px">{{ useDetail.totalOrder || 0 }}条</span>
      </div>
      <div class="dialog_content_item">
        Device Total Income:
        <span style="margin-left:5px">{{ useDetail.totalMoney || 0 }}元</span>
      </div>
      <div class="engaged">
        <div class="engaged_title">
          <div class="content">仓位</div>
          <div class="cell_state">
            <!--没Battery   class="nocell",有Battery incell,已充满 abound,异常 abnormal-->
            <div class="">
              <img class="imgss" src="/public/images/battery1.png" alt="" />No
              Battery
            </div>
            <div class="">
              <img class="imgss" src="/public/images/battery2.png" alt="" />Have
              Battery
            </div>
            <div class="">
              <img
                class="imgss"
                src="/public/images/battery3.png"
                alt=""
              />已充满
            </div>
            <div class="">
              <img class="imgss" src="/public/images/battery4.png" alt="" />异常
            </div>
          </div>
        </div>

        <!-- 
					<el-checkbox-group class="engaged_group" v-model="checkboxGroup">
						<el-checkbox-button
						
						>{{ item.cabinetNo }}号仓</el-checkbox-button>
					</el-checkbox-group>-->

        <el-radio-group
          fill="#9a9c1b"
          class="engaged_group"
          v-model="checkboxGroup"
          @change="buttonFn(checkboxGroup)"
        >
          <el-radio-button
            :class="['engaged_item', 'bg_span_' + item.status]"
            v-for="item in useDetail.engaged"
            :label="item.cabinetNo"
            :key="item.cabinetNo"
          >
            <div>{{ item.cabinetNo }}号仓</div>
            <div
              :class="
                item.cabinetStatus === 1 ? 'twoDivColor1' : 'twoDivColor2'
              "
            >
              {{ item.cabinetStatus === 1 ? "开门" : "关门" }}
            </div>
            <div>
              {{
                item.status === 0
                  ? "没Battery"
                  : item.status === 1
                  ? "有Battery"
                  : item.status === 2
                  ? "已充满"
                  : "故障仓"
              }}
            </div>
            <div v-for="i in list" :key="i.id">
              {{ item.id === i.id ? "电量：" + i.soc + "%" : "" }}
            </div>
            <p>
              <span>EnableStatus：</span>
              <el-switch
                v-model="item.disableStatus"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                @change="switchChange(item)"
                inactive-color="#ff4949"
              ></el-switch>
            </p>
            <p>柜门Temperature：{{ item.temperature }}度</p>

            <!-- <div class="item" v-for="item in list">
           
            <ul>
              <li>
                <p>
                  <span>EnableStatus：</span>
                  <el-switch v-model="item.disableStatus" :active-value="1" :inactive-value="0" active-color="#13ce66"
                    @change="switchChange(item)" inactive-color="#ff4949"></el-switch>
                </p>
                <p>柜门Temperature：{{ item.temperature }}度</p>
              </li>
 
            </ul>
          </div> -->
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <p style="margin-bottom:10px">
      DevicePosition坐标 经度：{{ useDetail.lng }} 纬度：{{ useDetail.lat }}
    </p>
    <baidu-map
      style="width:100%;height:350px"
      class="map-wrap"
      :center="mapData.center"
      :zoom="mapData.zoom"
      @ready="mapHandler"
    ></baidu-map>

    <span slot="footer" class="dialog-footer">
      <el-button type="success" @click="buttonClick('开仓')">开仓</el-button>
      <el-button type="primary" @click="buttonClick('通电')">通电</el-button>
      <el-button type="info" @click="buttonClick('关电')">关电</el-button>
      <el-button @click="$emit('update:visible', false)">Cancel</el-button>
    </span>
  </el-dialog>
</template>
<script>
import baidumap from "../../js/baidumap";
export default {
  data() {
    return {
      checkboxGroup: "",
      list: [],
      fag: true,
      timer: null,
      id: "",
      numSS: "",
      //地图Data
      mapData: {
        //中心坐标
        center: { lng: 0, lat: 0 },
        //缩放级别
        zoom: 20
      },
      //BMap类
      BMap: null,
      //地图对象
      map: null
    };
  },
  destroyed() {
    this.fag = false;
    clearInterval(this.timer);
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    useDetail: {
      type: Object,
      required: true
    },
    res: {}
  },
  mounted() {
    // this.useDetail.engaged.forEach((item) => {
    let spanItem = document.getElementsByTagName(
      "el-radio-group>el-radio-group"
    );
    console.log(2222222222, this.useDetail, this.useDetail.lng, this.res);

    // });
    this.id = this.res.id;
    this.getData();
    // this.timer = setInterval(() => {
    //   if (this.fag) {
    //     this.getData();
    //   }
    // }, 3000)
  },
  watch: {
    visible: {
      handler: function(status) {
        if (!status) {
          this.checkboxGroup = "";
        }
      },
      immediate: true, //关键
      deep: true
    }
  },
  methods: {
    // 拿到仓位号
    buttonFn(i) {
      console.log(567, i);
      this.numSS = i;
    },
    buttonClick(value) {
      console.log(value, "123");
      if (this.useDetail.deviceStatus == 2) {
        this.$message({
          message: "Device已Offline！",
          type: "warning"
        });
        return;
      } else if (this.useDetail.deviceStatus == 3) {
        this.$message({
          message: "Device已故障！",
          type: "warning"
        });
        return;
      }
      var openType = "";
      var openDoors = {};
      if (value === "开仓") {
        openType = 0;
      } else if (value === "通电") {
        openType = 1;
      } else if (value === "关电") {
        openType = 2;
      }
      // 拿到该仓位的Battery号
      let arr = this.useDetail.engaged;
      let num = this.numSS - 1;
      let Objs = arr[num];
      // console.log(8888, num, arr, Objs);
      openDoors = {
        deviceNo: this.useDetail.deviceNo, //Device Number
        handlerType: openType, // 0开门 1开电 2关电
        cabinetNo: this.checkboxGroup, //柜子号
        batteryNo: Objs.goodsNo || ""
      };

      if (this.checkboxGroup) {
        this.$confirm(
          "是否要为" + this.checkboxGroup + "号仓" + value + "?",
          "Hint",
          {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          }
        ).then(async () => {
          const res = await this.apis.deviceDoorPowerOns(openDoors);
          console.log("开仓---", res);
          if (res.code == 200) {
            this.$message({
              message: value + "Success",
              type: "success"
            });
            this.$emit("update:visible", false);
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
          openType = "";
          openDoors = {};
        });
      } else {
        this.$message({
          message: "Please Select柜子号！",
          type: "warning"
        });
      }
    },

    selected() {
      // console.log("checkboxGroup---", this.checkboxGroup);
      // engaged.map(item => {
      // 	checkboxGroup.forEach(value => {
      // 		console.log(value);
      // 		if (item.cabinetNo == value) {
      // 			item.checked = true
      // 		} else {
      // 			item.checked = false
      // 		}
      // 	})
      // 	return item
      // })
      // console.log("engaged---", engaged);
      // console.log("checkboxGroup-----", checkboxGroup);
    },

    formatSeconds(value) {
      var theTime1 = parseInt(value); // 需要转换的时间分钟
      var theTime2 = 0; // 小时
      var theTime3 = 0; // 天

      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60);
        if (theTime2 > 24) {
          // 大于24小时
          theTime3 = parseInt(theTime2 / 24);
          theTime2 = parseInt(theTime2 % 24);
        }
      }
      var result = "";
      if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + "分钟";
      }
      if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + "小时" + result;
      }
      if (theTime3 > 0) {
        result = "" + parseInt(theTime3) + "天" + result;
      }
      return result;
    },
    async getData() {
      var res = await this.apis.device_channelList({
        id: this.id
      });
      this.list = res.data || [];
    },
    async switchChange(item) {
      const res = await this.apis.device_updateDisable({
        id: item.id
      });

      this.$message({
        message: "Operations Success！",
        type: "success"
      });
    },

    // 地图
    //地图预处理
    async mapHandler({ BMap, map }) {
      setTimeout(async () => {
        if (this.businessId) {
          //可以在此处请求接口获取坐标Data
          await this.getMallBusinessDetail();
        }
        //Save百度地图类
        this.BMap = BMap;
        //Save地图对象
        this.map = map;

        // 按住鼠标右键，修改倾斜角和角度
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        // map.setHeading(64.5);   //Setup地图旋转角度
        // map.setTilt(73);       //Setup地图的倾斜角度

        //如果一开始坐标存在(Edit的时候)
        // if (this.useDetail.lng && this.useDetail.lat) {

        //Setup坐标
        // 后端传的经纬度是国测的，转为百度经纬度
        let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
        let x = this.useDetail.lng;
        let y = this.useDetail.lat;
        let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        this.useDetail.lng = z * Math.cos(theta) + 0.0065;
        this.useDetail.lat = z * Math.sin(theta) + 0.006;
        this.mapData.center.lng = this.useDetail.lng;
        this.mapData.center.lat = this.useDetail.lat;
        console.log(8888888);

        // }
        // else {
        //   console.log(999999999);
        //   //如果坐标不存在则动态获取Current浏览器坐标（创建的时候）
        //   let geolocation = new BMap.Geolocation()
        //   //获取Current的坐标（Employpromise 将异步转换为同步）
        //   await new Promise((resolve) => {
        //     geolocation.getCurrentPosition((r) => {
        //       this.mapData.center.lng = this.useDetail.lng =
        //         r.point.lng
        //       this.mapData.center.lat = this.useDetail.lat = r.point.lat
        //       resolve()
        //     })
        //   })
        // }
        //创建定位标记
        let marker = new BMap.Marker(
          new BMap.Point(this.useDetail.lng, this.useDetail.lat)
        );
        //将标记Add到地图上
        map.addOverlay(marker);
      }, 1500);
    }
  }
};
</script>

<style lang="scss">
.dialog_content_item {
  margin-bottom: 10px;
  font-size: 18px;
  display: flex;
  align-content: center;
}

.dialog_content_item > span {
  color: #3e8ef7;
  font-size: 20px;
}

.engaged {
}

.engaged_group {
  display: flex;
  // justify-content: space-around;
  // font-size: 0.83rem;
  flex-wrap: wrap;
}

.engaged .engaged_title {
  margin-bottom: 20px;
  display: flex;
  align-items: baseline;
}

.engaged .cell_state {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.engaged .cell_state > div {
  margin-right: 20px;
}

.engaged .cell_state .incell::before,
.engaged .cell_state .nocell::before,
.engaged .cell_state .abound::before,
.engaged .cell_state .abnormal::before {
  content: "";
  display: inline-block;
  width: 15px;
  height: 15px;
  margin-right: 5px;
  background-color: #eb0c0c;
}

.engaged .cell_state .nocell::before {
  background-color: #e5e5e5;
}

.engaged .cell_state .abound::before {
  background-color: #37f31e;
}

.engaged .cell_state .abnormal::before {
  background-color: #2c39e7;
}

.engaged .engaged_title > div {
  font-size: 18px;
  display: flex;
  align-items: center;
}

.engaged .engaged_title .content {
  font-size: 22px;
  font-weight: 500;
  margin-right: 20px;
  font-weight: 700;
}

.engaged .engaged_item {
  width: 160px;
  color: #fff;
  font-size: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  border-radius: 10%;

  box-shadow: -2px -2px 5px #444, 2px 2px 5px #222, inset 2px 2px 4px #444,
    inset -2px -2px 4px #222;
  font-family: "Damion", cursive;
  border: none;
  transition: 500ms;
  // box-shadow: 0px 2px 6px 0 #000;

  div {
    line-height: 23px;
    font-size: 18px;
  }

  p {
    line-height: 23px;
    font-size: 16px;
  }

  .twoDivColor2 {
    // color: #3e8ef7;
  }

  .twoDivColor1 {
    color: #eb2907;
  }
}

.el-radio-button__inner {
  width: 100%;
  border: 1px solid #dcdfe6;
}

.bg_span_0 span {
  background-color: #e5e5e5;
}

.bg_span_1 span {
  background-color: #eb0c0c;
}

.bg_span_2 span {
  background-color: #37f31e;
}

.bg_span_3 span {
  background-color: #2c39e7;
}

.bg_span_4 span {
  background-color: #101080;
}

.imgss {
  width: 50px;
  height: 50px;
}

#l-map {
  height: 250px;
  width: 100%;
}
</style>
